package com.stock;

import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;

import com.utils.CONST;

// hold all the stock data
public class Stock {
	
	// stock name
	public String name;
	
	// date from different days
	public LinkedList<StockData> dataList;
	
	// c'tor
	public Stock(String name) {
		this.name = name;
		this.dataList = new LinkedList<StockData>();
		stockByName.put(name, this);
	}
	
	// get data of specific day (if exist) 
	public StockData getDay(int day){
		if(day < getDayNumber()){
			return dataList.get(day);
		}else{
			return null;
		}
	}
	
	// return the amount of days with data
	public int getDayNumber(){
		return dataList.size();
	}
	
	public String getName() {
		return name;
	}
	
	// add day data
	public void addData(StockData data){
		dataList.add(data);
	}

	// add day data
	public void addData(Long time, Double openPrice, Double hightPrice,
						Double lowPrice, Double closingPrice, Long volume){
		
		double avgValue[] = new double[CONST.avgNumDays.length] ;
		
		StockData last = null;
		if(dataList.size()>0){
			last = dataList.getLast();
		}
		
		int size = dataList.size() ;
		for (int i = 0; i < CONST.avgNumDays.length; i++) {
			int avgDays = CONST.avgNumDays[i];
			if(size < (avgDays  -1)){
				avgValue[i] =closingPrice;	
				
			}else if(size == (avgDays -1)){
				double sum =0; 
				for (StockData stc : dataList) {
					sum+=stc.getClosingPrice();
				}
				sum+=closingPrice;
				sum/=avgDays;
				avgValue[i] =sum;
				
			}else{
				double sum = last.getAvg(avgDays);
				sum  = sum * avgDays ;
				sum += closingPrice;
				StockData rem = dataList.get(size-avgDays);
				if(rem!=null){
					sum-=rem.getClosingPrice();
				}
				sum /=avgDays;
				avgValue[i] = sum;
			}
		}
		HashMap<Integer,Double> avg =new HashMap<Integer, Double>(); 
		for (int i = 0; i < CONST.avgNumDays.length; i++) {
			avg.put(CONST.avgNumDays[i],avgValue[i]);
		}
		
		dataList.add(new StockData(time, openPrice, hightPrice, lowPrice, closingPrice, volume, avg));
	
	}
	
	// static!!!!  all stocks indexed by name...
	public static HashMap<String, Stock> stockByName = new HashMap<String, Stock>();
	public static Stock getStockByName(String name){
		return stockByName.get(name);
	}
	public static Collection<Stock> getAllStocks(){
		return stockByName.values();
	}
}
